<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8" />
	<meta name="viewport"
		content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
	<link rel="stylesheet" href="./css/reset.css">
	<link rel="stylesheet" href="./css/login.css">
	<link rel="icon" href="./icon/title_vagetable.png">
	<title>登录页面</title>
	<script src="./js/axios.min.js"></script>
	<script src="./js/axios.config.js"></script>
</head>

<body>
	<div class="icon">
		<img src="./img/login/logo.png" alt="">
	</div>
	<div class="infomation">
		<form class="login_form">
			<input name="username" pattern="/\w{3,}/" data-error="用户名不符合规范！" placeholder="用户名" type="text">
			<input name="password" pattern="/\d{3,}/" data-error="密码不符合规范！" placeholder="请输入密码" type="password">
			<button id="login" type="button">登录</button>
		</form>
	</div>

	<div class="function">
		<div class="forgetPassword"><a href="#">忘记密码？</a></div>
		<div class="registration"><a href="./register.html">注册</a></div>
	</div>
	<div class="other">
		<div class="title">其他登录方式</div>
		<ul>
			<li>
				<a href="#">
					<img src="./img/login/icon1.png" alt="">
					<div class="tag">微信</div>
				</a>
			</li>
			<li>
				<a href="#">
					<img src="./img/login/icon3.png" alt="">
					<div class="tag">QQ</div>
				</a>
			</li>
			<li>
				<a href="#">
					<img src="./img/login/icon2.png" alt="">
					<div class="tag">微博</div>
				</a>
			</li>
		</ul>
	</div>
	<script>
		// 查找元素
		let oUsername = document.querySelector('input[name="username"]')
		let oPassword = document.querySelector('input[name="password"]')

		// 表单验证函数
		function handleValidate() {
			// 提取正则字符串
			let reg_str = this.pattern.slice(1, -1);
			let isValid = new RegExp(reg_str).test(this.value);

			isValid ? this.style.borderColor = 'green' : (this.style.borderColor = '#c55a5c', alert(this.dataset.error))
			// 校验标记
			this.validate = isValid;
		}
		// 账号验证
		oUsername.addEventListener('blur', handleValidate)
		// 密码验证
		oPassword.addEventListener('blur', handleValidate)

		//点击登录事件函数
		let oLogin = document.querySelector('#login')
		oLogin.addEventListener('click', function () {

			// let oForm = document.querySelector('.login_form')
			// // 表单中每一项都需要设置name（与API文档一致）
			// let formData = new FormData(oForm)
			// //查看表单中的数据
			// for (const key of formData) {
			// 	console.log(key)
			// }
			
			let name = oUsername.value
			let pwd = oPassword.value
			// 校验所有表单
			let all_valid = oUsername.validate && oPassword.validate
			if (!all_valid) {
				alert('表单校验失败，请重新填写！')
				return
			}
			axios.post('/user/login', {
				username: name,
				password: pwd
			}).then((res) => {
				console.log(res)
				// 判断是否成功
				if (res.status) {
					alert('登录成功')
					sessionStorage.id = res.data.id
					sessionStorage.token = res.data.token
					// 跳转首页页面
					location.assign('./index.html')
				} else {
					alert(res.msg)
				}
			}).catch(function (err) {
					console.log(err)
				})
		})
	</script>
</body>

</html>